const uniPush = uniCloud.getPushManager({appId:"__UNI__178BE25"})
const uniIdCommon = require('uni-id-common')
const db = uniCloud.database();
const dbCmd = db.command
// 验证身份
const verifyIdentity = async (_this) => {
	/*先校验token（用户身份令牌）是否有效，并获得用户的_id*/
	// 获取客户端信息
	_this.clientInfo = _this.getClientInfo()
	// console.log(_this.clientInfo);

	// 定义uni-id公共模块对象
	_this.uniIdCommon = uniIdCommon.createInstance({
		clientInfo: _this.clientInfo
	})
	// 校验token（用户身份令牌）是否有效，并获得用户的_id
	let res = await _this.uniIdCommon.checkToken(_this.clientInfo.uniIdToken)
	// console.log('res',res);
	// if (res.errCode) {
	// 	// 如果token校验出错，则抛出错误
	// 	throw res
	// } else {
	// 	// 通过token校验则，拿去用户id
	// 	_this.current_uid = res.uid
	// }
	// console.log('current_uid', _this.current_uid);
	if (res.uid) {
		return res.uid
	} else {
		return res
	}
}
const updatePlayer = async (uids,uid) => {
	console.log('uids',uids,uid);
	return await uniPush.sendMessage(
	{
		"user_id":uids,
		"title":uid,
		"content":uids.length+'',
		"payload":{text:uid}
	}
	)
}
module.exports = {
	
	_before: async function() {
		this.clientInfo = this.getClientInfo()
		// console.log(this.clientInfo);

		// 定义uni-id公共模块对象
		this.uniIdCommon = uniIdCommon.createInstance({
			clientInfo: this.clientInfo
		})
		// 校验token（用户身份令牌）是否有效，并获得用户的_id
		let res = await this.uniIdCommon.checkToken(this.clientInfo.uniIdToken)
		console.log('预处理 _before', res);
		if (!res.uid) {
			throw new Error('token不存在')
			return res
		}
	},

	// 创建对局
	// createMatch(password) {

	// }
	// 加入对局
	async joinMatch(roomid) {
		let _this = this
		let uid = await verifyIdentity(_this)
		if (typeof uid == 'string') {
			const result = await db.collection('card-room').where({
				'roomid': roomid,
			}).update({
				user_id_list: dbCmd.push(uid)
			})
			console.log('云对象打印', result);
			return result
		}
		// db.collection('uni-id-users')



	},
	// shortExit
	async shortExit(){
		let _this = this
		let uid = await verifyIdentity(_this)
		if (typeof uid == 'string') {
			const result = await db.collection('card-room').where({
				online_num: uid
			}).get()
			console.log('云对象打印退出',result);
			// let obj = result.data[0].online_num.finc(e=>e==uid)
			let arr = result.data[0].online_num.filter(e=>e!=uid)
			let res = await db.collection('card-room').where({
				'online_num': uid,
			}).updateAndReturn({
				// updateAndReturn修改并返回值
				//dbCmd.inc 自增num
				online_num: arr
			})
			return result
		}
	},
	// 删除房间
	async deleteRoom(){
		let _this = this
		let uid = await verifyIdentity(_this)
		if (typeof uid == 'string') {
			const result = await db.collection('card-room').where({
				online_num: uid
			}).remove()
			return result
			console.log('云对象打印删除',result);
		}
	},
	// 当前在线人数,和牌信息
	async onlineInfo(roomid,push_clientid) {
		let _this = this
		let uid = await verifyIdentity(_this)
		if (typeof uid == 'string') {
			// db.collection('uni-id-users')
			const result = await db.collection('card-room').where({
				'roomid': roomid,
			}).get()
			let arr = []
			console.log('result.data.online_num',result.data[0].online_num);
			if(!result.data[0].online_num.includes(uid)){
				console.log('他不包含就新push');
				let res = await db.collection('card-room').where({
					'roomid': roomid,
				}).updateAndReturn({
					// updateAndReturn修改并返回值
					//dbCmd.inc 自增num
					online_num: dbCmd.push(uid)
				})
				console.log('云对象打印他不包含就新', res);
				updatePlayer(res.doc.online_num,uid)
				
				return res
			}else{
				console.log('包含');
				console.log('云对象打印', result);
				updatePlayer(result.data[0].online_num,uid)
			
				return result
			}
			
		}


	}
	// // 牌记录
	// async recordCard() {

	// }
	// // 推送所有人
	// async push() {

	// }

	// return await uniPush.sendMessage({
	// 		"push_clientid": "77aa4c79a55a836992e1a3be6f4c8254", 	//填写上一步在uni-app客户端获取到的客户端推送标识push_clientid
	// 		"title": "通知栏显示的标题",	
	// 		"content": "通知栏显示的内容",
	// 		"payload": {
	// 			"text":"体验一下uni-push2.0"
	// 		}
	// 	})
};